<?php

//查询报名人数
function voteUserList($acid) {

    $where['state'] = 2;
    $where['activity_id'] = $acid;
    echo M('User')->where($where)->count();
}

//查询投票人数
function voteJoinList($acid) {
    $where['state'] = 2;
    $where['activity_id'] = $acid;
    echo M('Vote_recode')->where($where)->count();
}

//查询投票人数
function voteJoinList__($acid) {
    $where['state'] = 2;
    $where['activity_id'] = $acid;
    return M('Vote_recode')->where($where)->count();
}

//查询访问量
function voteBrowse($acid) {

    $data = json_decode(file_get_contents(__DIR__ . "/" . $acid . "browse.json"), true);
    echo $data['browse'] ? $data['browse'] : 0;
    if ('index' == ACTION_NAME || 'detail' == ACTION_NAME) {
        if ($data['browse'] - voteJoinList__($acid) <= 500) {
            $num = 500;
        } else {
            $num = 1;
        }
        $hit = $data['browse'] + $num;
        $data = json_decode('{"browse":"' . $hit . '"}');
        $fp = fopen(__DIR__ . "/" . $acid . "browse.json", "w");
        fwrite($fp, json_encode($data));
        fclose($fp);
    }
    // echo ACTION_NAME;exit;
}

function charReplace($str) {
    return "&emsp;&emsp;" . str_replace("<br />", "<br />&emsp;&emsp;", $str);
}

//微信文件下载
function wxdownMediAapi($mediaid) {
    if (!empty($mediaid)) {
        $access_token = wx_access_token();
        //下载图片
        $url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=$access_token&media_id=$mediaid";
        $fileInfo = downloadWeixinFile($url);
        $filename = uniqid('user_') . '.jpg';
        saveWeixinFile($filename, $fileInfo["body"]);
        return './uploads/' . $filename;
    } else {
        return false;
    }
}

/**
 * 下载微信图片
 * @param type $url
 * @return type
 * 
 */
function downloadWeixinFile($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_NOBODY, 0);    //只取body头
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $package = curl_exec($ch);
    $httpinfo = curl_getinfo($ch);
    curl_close($ch);
    $imageAll = array_merge(array('header' => $httpinfo), array('body' => $package));
    return $imageAll;
}

/**
 * 保存本地
 * @param type $filename
 * @param type $filecontent
 * 
 */
function saveWeixinFile($filename, $filecontent) {
    $path = './uploads/';
    if (!file_exists($path)) {
        mkdir($path, 0777);
    }
    $local_file = fopen($path . $filename, 'w');
    if (false !== $local_file) {
        if (false !== fwrite($local_file, $filecontent)) {
            fclose($local_file);
        }
    }
}


function check_verify($code, $id = ''){
    $verify = new \Think\Verify();
    return $verify->check($code, $id);
}